<template>
	<view class="appraise-content" :style="{direction:i18nLocale=='ug'?'rtl':''}">
		<HeaderTitle :title="$t('NearbyAddresses')" :bottom="true" :lang="false" :mobile="false" :combakflag="true"
			dir="ltr"></HeaderTitle>
		<view class="map-content">
			<map :latitude="latitude" :longitude="longitude" enable-zoom scale="18" style="width: 100%; height:100%;"
				show-location :markers="markers" @regionchange="changetab" @markertap="changemarker">
				<image class="map-marker" :src="markerIcon"></image>
			</map>
		</view>
		<view class="myaddres">
			<view class="title">{{$t('CurrentPositioning')}}</view>
			<view class="address-content">
				<text>{{i18nLocale=='ug'?storeValue.ug_name:storeValue.cn_name}}</text>
				<u-icon  @click="reflashlocation" name="reload" color="#209f5a" size="28"></u-icon>
			</view>
		</view>
		<view class="title">
			<u-icon name="map-fill" color="#209f5a" size="28"></u-icon>
			<text>{{$t('NearbyAddresses')}}</text>
			<view style="font-size: 20rpx;white-space:nowrap;" v-if="topsList.length">( {{$t('NearestDistance')}}
				{{topsList[0].distance>=1?topsList[0].distance.toFixed(2)+'km':topsList[0].distance.toFixed(2)*1000+'m'}}
				)
			</view>
		</view>
		<scroll-view scroll-y="true" class="myscroll">
			<view class="pois" v-if="nearList.length>0" v-for="(item,index) in nearList" @click="selecetPois(item)">
				<view class="ad_title" :style="{direction:i18nLocale=='ug'?'rtl':''}">
					<view class="">{{i18nLocale=='ug'?item.ug_name:item.cn_name}}</view>
					<u-icon v-if="item.id==selecet_id" name="checkmark" color="#45bc1b" size="25"></u-icon>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import {
		gettops,
		getcommunities
	} from '@/api/all.js';
	import HeaderTitle from "@/components/HeaderTitle.vue"
	var jweixin = require('jweixin-module');
	import jwx from '@/utils/jwx.js'
	export default {
		components: {
			HeaderTitle
		},
		data() {
			return {
				selecet_id: 0,
				topsList: [],
				defaulttopsList: [],
				nearList: [],
				commonList: [],
				latitude: '39.62612',
				longitude: '76.58755',
				markerIcon: require('@/static/images/marker.png'),
				markers: []
			};
		},
		onLoad() {
			uni.setNavigationBarTitle({
				title: this.$t('NearbyAddresses')
			})
			if (!this.$store.state.location) {
				this.getlocation();
			} else {
				console.log(this.$store.state.location, '+++++++')
				this.latitude = this.$store.state.location[0];
				this.longitude = this.$store.state.location[1];
				this.getTops();
			}

		},
		mounted() {},
		computed: {
			i18nLocale() {
				return this.$i18n.locale;
			},
			storeValue() {
				return this.$store.state.address;
			},
		},
		methods: {
			//获取位置
			getlocation() {
				let that = this;
				jwx.initJssdk();
				jweixin.ready(function() {
					jweixin.getLocation({
						type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'  
						success: function(res) {
							that.latitude = res.latitude;
							that.longitude = res.longitude;
							that.$store.commit('setLocation', [res.latitude, res.longitude]);
							that.getTops();
						},
						fail: function(res) {
							alert('失败',res)
							// console.log(res, '++++++++++')
						},
					});
				})
			},
			//刷新位置
			reflashlocation() {
				let that = this;
				jwx.initJssdk();
				jweixin.ready(function() {
					jweixin.getLocation({
						type: 'gcj02', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'  
						success: function(res) {
							that.latitude = res.latitude;
							that.longitude = res.longitude;
							that.$store.commit('setLocation', [res.latitude, res.longitude]);
						},
						fail: function(res) {
							// console.log(res, '++++++++++')
						},
					});
				})
			},
			//位置移动
			changetab(e) {
				if (e.target.centerLocation) {
					var mylocation = e.target.centerLocation;
					if (mylocation) {
						this.latitude = mylocation.latitude;
						this.longitude = mylocation.longitude;
						let lnglat = mylocation.latitude + ',' + mylocation.longitude;
						this.nearDistance(this.defaulttopsList, this.latitude, this.longitude)

					}
				}

			},
			//点击标注
			changemarker(e) {
				let id = e.detail.markerId;

				this.selecetPois(this.commonList.filter(item => item.id === id)[0]);
				// e.detail.id
			},
			getTops() {
				let that = this;
				gettops({
					area_code: 653101
				}).then(res => {
					let data = res.body.data;
					this.defaulttopsList = data;
					this.nearDistance(data, this.latitude, this.longitude)
					this.getCommunities(data);
				})
			},
			getCommunities(tops) {
				let that = this;
				let common = [];
				let newdata = tops.map((item, index) => {
					common.push(item.communities)
				})

				this.commonList = [...new Set(common.flat())];
			
				let data = this.commonList
				for (let i = 0; i < data.length; i++) {
					if (that.$i18n.locale == 'ug') {
						that.markers.push({
							id: data[i].id,
							latitude: data[i].location[0],
							longitude: data[i].location[1],
							iconPath: require('@/static/images/lou.png'),
							width: 50,
							height: 50,
							label: {
								content: data[i].ug_name,
								color: '#fff',
								bgColor: '#15c45b',
								textAlign: 'center',
								padding: 10,
								borderRadius: 10,
								x: -90,
								y: -90
							}
						})
					} else {
						that.markers.push({
							id: data[i].id,
							latitude: data[i].location[0],
							longitude: data[i].location[1],
							iconPath: require('@/static/images/lou.png'),
							width: 50,
							height: 50,
							label: {
								content: data[i].cn_name,
								color: '#fff',
								bgColor: '#15c45b',
								textAlign: 'center',
								padding: 10,
								borderRadius: 10,
								x: -90,
								y: -90
							}
						})
					}
				}
				console.log(that.markers,'+++++++')
			},
			// 两点间距离
			distance(la1, lo1, la2, lo2) {
				var La1 = (la1 * Math.PI) / 180.0
				var La2 = (la2 * Math.PI) / 180.0
				var La3 = La1 - La2
				var Lb3 = (lo1 * Math.PI) / 180.0 - (lo2 * Math.PI) / 180.0
				var s = 2 * Math.asin(
					Math.sqrt(
						Math.pow(Math.sin(La3 / 2), 2) +
						Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)
					)
				)
				s = s * 6378.137 //地球半径
				s = Math.round(s * 10000) / 10000
				return s;
			},
			// 计算最近的距离
			nearDistance(array, centerLatitude, centerLongitude) {

				let newarry = array.map((item, index) => {
					//计算两个点的距离
					let d = this.distance(
						item.location[0],
						item.location[1],
						centerLatitude,
						centerLongitude
					)

					return {
						item: item,
						distance: d
					};

				})
				// 从近到远排序
				newarry.sort((a, b) => a.distance - b.distance);

				this.topsList = newarry;

				// let community_ids = this.topsList[0].item.community_ids.split(",");
				// let idArr = community_ids.map(Number);
				// 分配小区
				console.log(this.topsList[0].item, '++++++')
				// this.nearList = this.commonList.filter(element => idArr.includes(element.id));
				if (this.topsList[0].item.communities) {
					this.nearList = this.topsList[0].item.communities;
					this.$store.commit('setLocation', [centerLatitude, centerLongitude]);
				}
			},
			selecetPois(item) {
				this.$store.commit('setTopid', this.topsList[0].item.id);
				this.$store.commit('setAddress', item);
				this.selecet_id = item.id;
				uni.$emit('onBack', JSON.stringify(item));
				setTimeout(() => {
					uni.navigateBack({
						delta: 1 // 返回上一级页面
					});
				}, 200)
			}
		}

	}
</script>

<style lang="scss" scoped>
	.appraise-content {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		background-color: $uni-bg-color-box;
		font-weight: 200;

		.map-marker {
			width: 44rpx;
			height: 62rpx;
			position: absolute;
			top: 15vh;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.map-content {
			width: 100%;
			height: 30vh;
			position: relative;
		}

		.map-marker {
			width: 44rpx;
			height: 62rpx;
			position: absolute;
			top: 15vh;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.myaddres {
			display: flex;
			flex-direction: column;
			padding: 30rpx 0rpx;
			background-color: #fff;
			font-size: $uni-font-size-base;

			.title {
				color: $uni-text-color-grey;
				font-size: $uni-font-size-base;

				.nearest {
					font-size: $uni-font-size-sm0;
				}
			}

			.address-content {
				font-size: $uni-font-size-base;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding:0rpx 20rpx;

				text {
					width: 80%;
					font-size: $uni-font-size-base;
				}
			}

		}

		.centertitle {
			padding: $uni-spacing-padding-sm;
			background-color: #fff;
			color: $uni-text-color-grey;
			margin: 30rpx 0rpx;
			font-size: $uni-font-size-base;
		}

		.title {
			width: 100%;
			display: flex;
			align-items: center;
			padding: $uni-spacing-padding-sm;
			box-sizing: border-box;
			background-color: #fff;

			text {
				padding: 0rpx 10rpx;
				color: #9e9e9e;
				font-size: $uni-font-size-base;
			}
		}

		.myscroll {
			width: 100%;
			height: calc(100vh - (30vh + 410rpx));
			background-color: #fff;
		}

		.pois {
			width: 100%;
			display: flex;
			flex-direction: column;
			border-bottom: 2rpx solid $uni-border-color;
			padding: 30rpx 20rpx;
			box-sizing: border-box;
			font-size: $uni-font-size-base;

			.ad_title {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.ad_content {
				width: 100%;
				color: $uni-text-color-grey;
				font-size: 25rpx;
				white-space: nowrap;
				/* 不换行 */
				overflow: hidden;
				/* 溢出隐藏 */
				text-overflow: ellipsis;
				font-size: $uni-font-size-base;

			}
		}

	}
</style>